<?php
namespace api\utils;
use herosphp\core\Loader;
use herosphp\core\Log;
use herosphp\http\HttpClient;
use herosphp\string\StringUtils;
use herosphp\utils\AjaxResult;
use rsa\RSACrypt;
use rsa\SignUtil;

/**
 * 大塑支付系统API调用客户端
 * @author yangjian<yangjian102621@gmail.com>
 */
class PayApiClient {

    /**
     * 发送api调用请求
     * @param $uri
     * @param $params
     * @return AjaxResult
     */
    public static function send($uri, $params) {

        $client = new HttpClient();
        $url = getConfig('pay_api_url').$uri;
        $params['__timer'] = time();
        $params['__appid'] = appId();

        //build headers
        $headers = array('appName' => 'mpe');
        $tokens = Loader::config('token');
        $headers['token'] = $tokens[$headers['appName']];

        $sign = SignUtil::sign($url, $params);
        $rsa = new RSACrypt();
        $params['__sign'] = $rsa->encryptByPublicKey($sign);
        try {
            $result =  $client->post($url, $params, $headers);
        } catch ( \Exception $e ) {
            Log::error($e);
            return AjaxResult::fail($e->getMessage());
        }
        if( !is_json($result)){
            Log::error("APIReturnNotJsonException:".$result);
        }
        $result = StringUtils::jsonDecode($result);

        return new AjaxResult($result['code'], $result['message'], $result['data']);
    }

}
